<template>
  <div>
    <h2>
      {{ status }}<span>{{ filterArr.length }}</span>
    </h2>
    <ol>
      <li
        :class="item.checked == true ? 'disable' : ''"
        v-show="item.checked == show"
        v-for="(item, index) in arr"
        :key="index"
      >
        <input type="checkbox" v-model="item.checked" />
        <!-- 在点击p表标签时进入编辑的状态 -->
        <input
          v-show="item.show"
          ref="input"
          @blur="edit(index)"
          v-model="item.val"
          style="width: 80%; margin-left: 30px"
        />
        <!-- 不是编辑状态 -->
        <p v-show="!item.show" @click="appear(index, item.val)">
          {{ item.val }}
        </p>
        <a href="javascript:;" @click="del(index)">-</a>
      </li>
    </ol>
  </div>
</template>
<script>
import { computed, nextTick, ref, watch } from "vue";
export default {
  props: ["status", "arr"],
  setup(props, { emit }) {
    let input = ref(null);

    // 判断显示完成数据还是未完成数据
    let show = props.status === "已完成" ? true : false;
    // 过滤出该组件渲染的数据
    let filterArr = [];
    filterArr = computed(() => {
      return (filterArr = props.arr.filter((item) => {
        return item.checked == show;
      }));
    });
    // 点击p标签显示input标签
    // 点击input框的文字
    let text = "";
    const appear = (index, val) => {
      text = val;
      emit("editShow", { index, show: true });
      nextTick(() => {
        input.value[index].focus();
      });
    };
    // input失去焦点后保存数据
    const edit = (index) => {
      if (input.value[index].value.trim() == "") {
        input.value[index].value = text;
      }
      emit("edit", {
        index,
        obj: { val: input.value[index].value, show: false, checked: false },
      });
    };
    // 删除当前数据
    const del = (index) => {
      emit("del", index);
    };
    return {
      input,
      filterArr,
      appear,
      edit,
      show,
      del,
    };
  },
};
</script>
<style scoped>
.disable {
  opacity: 0.5;
}
</style>
